/**  
 * Copyright © 2017武汉思恒达科技有限公司. All rights reserved.
 * @Title: DownloadFileUtil.java
 * @Prject: Ads
 * @Package: com.loongtek.onyx.corgi.web.ads.utils
 * @author: int_java_se@163.com
 * @date: 2017年3月7日 下午2:10:27
 */
package com.thinkingstar.iads.common.utils;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.lang.Encoding;
import org.nutz.log.Log;
import org.nutz.log.Logs;

/** 
 * @ClassName: DownloadFileUtil <br/> 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @date: 2017年3月7日 下午2:10:27 <br/> 
 * @author int_java_se@163.com
 * @version  
 * @since JDK 1.7
 */
public class DownloadFileUtil {
	private static Log log = Logs.get();
	/**
	 * 将相应设置成下载流
	 * @param file 文件
	 * @param fileName 文件名称
	 * @param req 请求
	 * @param resp 相应
	 */
	public static void webDownloadFileUtil(File file,String fileName,HttpServletRequest req, HttpServletResponse resp) {
		resp.setContentType("application/x-download charset=UTF-8");
		try {
			if ("FF".equals(getBrowser(req))) {
				// 是不是火狐浏览器
				fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
			} else {
				fileName = URLEncoder.encode(fileName, Encoding.UTF8);
			}
		} catch (UnsupportedEncodingException e) {
			fileName = file.getName();
		}
		resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
	}

	public static String getFileName(String sFilePath)
	{
		int sEnd = sFilePath.length();
		int sStart = sFilePath.lastIndexOf("\\") + 1;
		int sStart2 = sFilePath.lastIndexOf("/") + 1;
		if (sStart < sStart2 ){
			sStart = sStart2;
		}
		String fileN = sFilePath.substring(sStart, sEnd);
		return fileN;
	}
	public static int getFileSize(String sFilePath)
	{
		File f=new File(sFilePath);
		return (int)f.length();
	}
	/**
	 * 将相应设置成文件流
	 * @param req 请求
	 * @param resp 相应
	 */
	public static void fileStream(String filePath,HttpServletRequest req, HttpServletResponse resp){
		try {
			filePath = URLDecoder.decode(filePath,"UTF-8");
			//******读取磁盘文件，输出文件流 开始*******************************
			log.info("fileStream--------------------------------"+filePath);
			String fileName = getFileName(filePath);
			int fileSize = getFileSize(filePath);

			resp.reset();
			resp.setContentType("application/msword"); // application/x-excel, application/ms-powerpoint, application/pdf
			resp.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
			resp.setContentLength(fileSize);

			OutputStream outputStream = resp.getOutputStream();
			InputStream inputStream = new FileInputStream(filePath);
			byte[] buffer = new byte[10240];
			int i = -1;
			while ((i = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, i);
			}
			outputStream.flush();
			outputStream.close();
			inputStream.close();
		} catch (UnsupportedEncodingException e) {
			log.info("UnsupportedEncodingException--------------------------------"+e.fillInStackTrace());
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			log.info("FileNotFoundException--------------------------------"+e.fillInStackTrace());
			e.printStackTrace();
		} catch (IOException e) {
			log.info("IOException--------------------------------"+e.fillInStackTrace());
			e.printStackTrace();
		}
		/*resp.setContentType("application/msword charset=UTF-8");
		try {
			if ("FF".equals(getBrowser(req))) {
				// 是不是火狐浏览器
				fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
			} else {
				fileName = URLEncoder.encode(fileName, Encoding.UTF8);
			}
		} catch (UnsupportedEncodingException e) {
			fileName = file.getName();
		}
		resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");*/
	}

	public static void downLoadFile(File file,String fileName,HttpServletRequest req, HttpServletResponse resp){
		webDownloadFileUtil(file,fileName,req,resp);
		BufferedInputStream bis = null;  
	    BufferedOutputStream bos = null;  
	    try {
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(resp.getOutputStream());  
		    byte[] buff = new byte[4096];  
		    int bytesRead;  
		      while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
		    bos.write(buff, 0, bytesRead);  
		        }  
		    bis.close();  
		    bos.close();  
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void batchDownLoadFile(List<File> fileList, String fileName, HttpServletRequest req, HttpServletResponse resp){
			try {
				fileName = java.net.URLEncoder.encode(fileName, "UTF-8");//防止ie下文件名乱码
				//在服务器端创建打包下载的临时文件
				String outFilePath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator;
				outFilePath += "test"+File.separator + fileName;
				log.debug("bag download。。。。。。+++++++"+outFilePath);
				File file = new File(outFilePath);
				// 文件是否存在
				if (!file.exists()) {
					file.createNewFile();
				}
				//文件输出流
				FileOutputStream outStream = new FileOutputStream(file);
				//压缩流
				ZipOutputStream toClient = new ZipOutputStream(outStream);
				//toClient.setEncoding("utf-8");
				zipFile(fileList, toClient);
				toClient.close();
				outStream.close();
				downloadFile(file, resp, true);
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

		/**
		 * 压缩文件列表中的文件
		 *
		 * @param files
		 * @param outputStream
		 * @throws IOException
		 */
		public  static void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException {
			List<String> fileNames=new ArrayList<>();
			try {
				int size = files.size();
			// 压缩列表中的文件
				for (int i = 0; i < size; i++) {
					File file = (File) files.get(i);
					String fileName=file.getName();
					log.debug("bag download。。。。。。++++++-------------+"+fileName);
					//判断压缩文件内文件名是否有重复
					if(!fileNames.contains(fileName)){
						fileNames.add(String.valueOf(i)+".docx");
					}else{
						fileName=file.getName().split(".")[0]+"(01)."+file.getName().split(".")[1];
					}
					zipFile(file, outputStream,fileName);
				}
			} catch (IOException e) {
				throw e;
			}
		}


		/**
		 * 将文件写入到zip文件中
		 *
		 * @param inputFile
		 * @param outputstream
		 * @throws Exception
		 */
		public static  void zipFile(File inputFile, ZipOutputStream outputstream,String fileName) throws IOException {
			try {
				if (inputFile.exists()) {
					if (inputFile.isFile()) {
						FileInputStream inStream = new FileInputStream(inputFile);
						BufferedInputStream bInStream = new BufferedInputStream(inStream);
						ZipEntry entry = new ZipEntry(fileName);
						outputstream.putNextEntry(entry);
						final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
						long streamTotal = 0; // 接受流的容量
						int streamNum = 0; // 流需要分开的数量
						int leaveByte = 0; // 文件剩下的字符数
						byte[] inOutbyte; // byte数组接受文件的数据
						streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
						streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
						leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量
						if (streamNum > 0) {
							for (int j = 0; j < streamNum; ++j) {
								inOutbyte = new byte[MAX_BYTE];
								// 读入流,保存在byte数组
								bInStream.read(inOutbyte, 0, MAX_BYTE);
								outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
							}
						}
						// 写出剩下的流数据
						inOutbyte = new byte[leaveByte];
						bInStream.read(inOutbyte, 0, leaveByte);
						outputstream.write(inOutbyte);
						outputstream.closeEntry(); // Closes the current ZIP entry
						// and positions the stream for
						// writing the next entry
						bInStream.close(); // 关闭
						inStream.close();
					}
				}
			} catch (IOException e) {
				throw e;
			}
		}


		/**
		 * 下载文件
		 *
		 * @param file
		 * @param response
		 */
		public static void downloadFile(File file, HttpServletResponse response, boolean isDelete) {
			try {
				// 以流的形式下载文件。
				BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				// 清空response
				response.reset();
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition","attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
				if (isDelete) {
					file.delete(); // 是否将生成的服务器端文件删除
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	/**
	 * 判断请求客户端浏览器类型
	 * @param request 请求
	 * @return 
	 */
	public static String getBrowser(HttpServletRequest request) {
		String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
		if (!UserAgent.isEmpty()) {
			if (UserAgent.indexOf("msie") >= 0)
				return "IE";
			if (UserAgent.indexOf("firefox") >= 0)
				return "FF";
			if (UserAgent.indexOf("safari") >= 0)
				return "SF";
		}
		return null;
	}
}
